package com.root.dreameraadmin.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.root.dreameraadmin.R;
import com.root.dreameraadmin.utils.AsyncGetDataUtil;
import com.root.dreameraadmin.utils.FileCacheUtil;
import com.root.dreameraadmin.utils.HttpConnectionUtil;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.text.ParseException;
import java.util.HashMap;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.root.dreameraadmin.view.ToolBarView.startIntroAnimation;


/**
 * Created by root on 16-7-22.
 */
public class PictureActivity extends AppCompatActivity {

    @Nullable
    @Bind(R.id.toolbar)
    Toolbar toolbar;
    @Bind(R.id.toolbar_text)
    TextView toolbar_textView;
    @Bind(R.id.ib_map)
    Button mapBtn;

    @Bind(R.id.picture_title)
    EditText picture_title;
    @Bind(R.id.picture_datetime)
    EditText picture_datetime;
    @Bind(R.id.picture_time_str)
    EditText picture_time_str;
    @Bind(R.id.picture_detail_title)
    EditText picture_detail_title;
    @Bind(R.id.picture_show)
    ImageView picture_iv;
    @Bind(R.id.choose_picture)
    Button choose_picture;

    private final String TAG = "PictureActivity";
    private Bitmap picture_map;
    String point_id;
    String url;
    HashMap<String, Object> pic_map = new HashMap<String, Object>();
    String picture_path;
    File file, newfile;
    boolean isChangePicture=false;
    String pic_id;
    String pic_name;
    private ProgressDialog progressDialog=null;

    @Override
    public void onCreate(Bundle savedInstanceState){
        Log.d(TAG,"onCreate()");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.picture_item);
        ButterKnife.bind(this);
        mapBtn.setVisibility(View.GONE);

        setSupportActionBar(toolbar);
        startIntroAnimation(toolbar, toolbar_textView, "编辑");

        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        pic_id = bundle.getString("id");
        String title = bundle.getString("title");
        picture_title.setText(title);
        url = bundle.getString("url");

        new getPictureTask().execute();
//        AsyncGetDataUtil.getPicFromServer(HttpConnectionUtil.PICTUREURl + "pic_id/", pic_id);
//        picture_map = AsyncGetDataUtil.getPicFromFile(pic_id);
//        picture_iv.setImageBitmap(picture_map);

        String datetime = bundle.getString("datetime");
        String time_str = bundle.getString("time_str");
        String detail_title = bundle.getString("detail_title");
        point_id = bundle.getString("point_id");

        picture_datetime.setText(datetime);
        picture_time_str.setText(time_str);
        picture_detail_title.setText(detail_title);
    }


    @OnClick(R.id.ib_back)
    public void clickBack() {
        finish();
    }

    @Override
    protected void onResume(){
        super.onResume();
        Log.d(TAG,"onResume");


        choose_picture.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View v) {
                Intent i = new Intent();
                i.setType("image/*");
                i.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(i,1);
            }
        });

    }


    @OnClick(R.id.submit)
    public void clickSubmit() {

        if (picture_title.getText().toString().equals("")
                || picture_time_str.getText().toString().equals("")) {
            Toast.makeText(PictureActivity.this,
                    "信息不完整哦~", Toast.LENGTH_SHORT).show();
            return ;
        }
        pic_map.put("title", picture_title.getText().toString());
        pic_map.put("datetime", picture_datetime.getText().toString() + "-01-01T01:01:00Z");
        pic_map.put("time_str", picture_time_str.getText().toString());
        pic_map.put("detail_url", picture_detail_title.getText().toString());
        pic_map.put("id",pic_id);

        new AlertDialog.Builder(PictureActivity.this)
                .setMessage("要添加这个图片吗")//设置显示的内容
                .setPositiveButton("添加", positiveListener)
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {//添加返回按钮
                    @Override
                    public void onClick(DialogInterface dialog, int which) {//响应事件
                        // TODO Auto-generated method stub
                        dialog.dismiss();
                    }
                }).show();//在按键响应事件中显示此对话框
    }


    public class getPictureTask extends AsyncTask<Void, Void, Void>{

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected Void doInBackground(Void... params) {
            AsyncGetDataUtil.getPicFromServer(url, pic_id);
            System.out.println("asdf picture_map "+ picture_map);

            while(picture_map == null){
                picture_map = AsyncGetDataUtil.getPicFromFile(pic_id);
            }

            return null;
        }

        @Override
        protected void onPostExecute(Void integer) {
            picture_iv.setImageBitmap(picture_map);
        }
    }


    Thread thread = new Thread(){
        public void run() {
            try{
                if (isChangePicture) {
                    HttpConnectionUtil.doPutPicture(HttpConnectionUtil.PICTUREURl + pic_id + "/", pic_map, newfile);
                    System.out.println("qwer " + HttpConnectionUtil.PICTUREURl + pic_id + "/");
                } else{
                    FileCacheUtil fileCacheUtil = new FileCacheUtil(FileCacheUtil.PICTUREPATH);
                    pic_name = fileCacheUtil.getPicFilename(pic_id);
                    file = new File(FileCacheUtil.PICTUREPATH + '/' + pic_name);
                    HttpConnectionUtil.doPutPicture(HttpConnectionUtil.PICTUREURl+pic_id+"/", pic_map, file);
                }
            }catch(Exception e){
                //
            }
            handler.sendEmptyMessage(0);
        }
    };

    final Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            progressDialog.dismiss();
            System.out.println("qwer result "+ HttpConnectionUtil.result);
            if (HttpConnectionUtil.result == "success") {
                Toast.makeText(PictureActivity.this, "上传成功！", Toast.LENGTH_SHORT).show();
                finish();
            } else {
                Toast.makeText(PictureActivity.this, "上传失败！", Toast.LENGTH_SHORT).show();
            }
            super.handleMessage(msg);
        }
    };


    public DialogInterface.OnClickListener positiveListener = new DialogInterface.OnClickListener(){

        @Override
        public void onClick(DialogInterface dialog, int which) {//确定按钮的响应事件
            //new thread to add
            progressDialog = ProgressDialog.show(PictureActivity.this, "","正在上传中...",true);
            thread.start();
        }
    };



    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        setSupportActionBar(toolbar);
        startIntroAnimation(toolbar, toolbar_textView, "添加图片");

        isChangePicture=false;
        System.out.println("asdf resultCode "+ resultCode);
        if (resultCode == RESULT_OK) {
            Uri uri;
            uri = data.getData();
            picture_path = getRealFilePath(PictureActivity.this, uri);
            Bitmap temp;

            try {
                newfile = new File(picture_path);
                FileInputStream fis = null;
                fis = new FileInputStream(newfile);
                int size =  fis.available();
                if(size/1024.0/1024.0 >= 0.5) {
                    Toast.makeText(PictureActivity.this,
                            "图片大小不能超过0.5M", Toast.LENGTH_SHORT).show();
                    finish();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            ContentResolver cr = this.getContentResolver();

            try {
                temp = BitmapFactory.decodeStream(cr.openInputStream(uri));
                if(temp.getHeight() > 1000 || temp.getWidth() > 1000){
                    picture_map = compressBmpFromBmp(temp);
                }else {
                    picture_map = temp;
                }
                picture_iv.setImageBitmap(picture_map);
               isChangePicture=true;
            } catch (FileNotFoundException e) {
                Log.e(TAG, e.getMessage(), e);
            }
        }else if(resultCode == RESULT_CANCELED) {
            finish();
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    public  String getRealFilePath(final Context context, final Uri uri) {
        if (null == uri) return null;
        final String scheme = uri.getScheme();
        String data = null;
        if (scheme == null)
            data = uri.getPath();
        else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
            data = uri.getPath();
        } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
            Cursor cursor = context.getContentResolver().query(uri, new String[]{MediaStore.Images.ImageColumns.DATA}, null, null, null);
            if (null != cursor) {
                if (cursor.moveToFirst()) {
                    int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
                    if (index > -1) {
                        data = cursor.getString(index);
                    }
                }
                cursor.close();
            }
        }
        return data;
    }

    private Bitmap compressBmpFromBmp(Bitmap image){
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 10, out);
        BitmapFactory.Options newOpts = new BitmapFactory.Options();
        int be = 3;
        newOpts.inSampleSize = be;
        ByteArrayInputStream isBm = new ByteArrayInputStream(out.toByteArray());
        image = BitmapFactory.decodeStream(isBm,  null ,  null );
        return image;
    }
}
